var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');

Page({
  data: {
    id: 0,
    ruleId: 0,
    goodsType: 0,
    goods: {},
    groupon: {},
    killEnd: '', //秒杀结束时间
    relatedGoods: [], //为您推荐
    cartGoodsCount: 0, //加入购物车
    memberList: [], //更多拼团
    openShare: false,
    shareImage: '',
    isGroupon: false, //标识是否是一个参团购买
    grouponLink: {}, //参与的团购
    soldout: false,
    hasStart:false,//是否开抢
    canWrite: false, //用户是否获取了保存相册的权限
    showAllModal: false,
    showOneModal: false
  },

  // 页面分享
  onShareAppMessage: function () {
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let shareUserId = 1;
    if (userInfo) {
      shareUserId = userInfo.userId;
    }
    console.log('分享地址：' + '/pages/index/index?goodId=' + this.data.id + '&shareUserId=' + shareUserId);
    return {
      title: that.data.goods.name,
      desc: '油桃优选分享',
      path: '/pages/index/index?goodId=' + this.data.id + '&shareUserId=' + shareUserId
    }
  },

  shareFriendOrCircle: function () {
    if (this.data.openShare === false) {
      this.setData({
        openShare: !this.data.openShare
      });
    } else {
      return false;
    }
  },
  handleSetting: function (e) {
    var that = this;
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '不授权无法保存',
        showCancel: false
      })
      that.setData({
        canWrite: false
      })
    } else {
      wx.showToast({
        title: '保存成功'
      })
      that.setData({
        canWrite: true
      })
    }
  },
  // 保存分享图
  saveShare: function () {
    let that = this;
    wx.downloadFile({
      url: that.data.shareImage,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            wx.showModal({
              title: '存图成功',
              content: '图片成功保存到相册了，可以分享到朋友圈了',
              showCancel: false,
              confirmText: '好的',
              confirmColor: '#a78845',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                }
              }
            })
          },
          fail: function (res) {
            console.log('fail')
          }
        })
      },
      fail: function () {
        console.log('fail')
      }
    })
  },

  //从分享的团购进入
  getGrouponInfo: function (grouponId) {
    let that = this;
    util.request(api.GroupOnJoin, {
      grouponId: grouponId
    }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          grouponLink: res.data.groupon,
          id: res.data.goods.id
        });
        //获取商品详情
        that.getGoodsInfo();
      }
    });
  },

  // 获取商品信息
  getGoodsInfo: function () {
    let that = this;
    util.request(api.GoodsDetail, {
      id: that.data.id
    }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          goodsType: res.data.goodsType,
          hasStart:res.data.hasStart,
          killEnd: res.data.killEnd,
          goods: res.data.info,
          groupon: res.data.groupon,
          shareImage: res.data.info.shareImage
        });

        //是否售空
        if (res.data.info.stock === 0) {
          that.setData({
            soldout: true
          });
        }

        WxParse.wxParse('goodsDetail', 'html', res.data.info.detail, that);
        //获取推荐商品
        that.getGoodsRelated();
      }
    });

    //更多拼团
    if (that.data.ruleId > 0) {
      util.request(api.GroupOnMember, {
        ruleId: that.data.ruleId
      }).then(function (res) {
        if (res.errno === 0) {
          that.setData({
            memberList: res.data
          });
        }
      });
    }
  },

  // 获取推荐商品
  getGoodsRelated: function () {
    let that = this;
    util.request(api.GoodsRelated, {
      id: that.data.id
    }).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          relatedGoods: res.data.goodsList,
        });
      }
    });
  },

  //获取选中的团购信息
  getCheckedGrouponValue: function () {
    let checkedValues = {};
    let _grouponList = this.data.groupon;
    for (let i = 0; i < _grouponList.length; i++) {
      if (_grouponList[i].checked) {
        checkedValues = _grouponList[i];
      }
    }
    return checkedValues;
  },

  getCheckedSpecKey: function () {
    let checkedValue = this.getCheckedSpecValue().map(function (v) {
      return v.valueText;
    });
    return checkedValue;
  },

  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: parseInt(options.id),
        ruleId: parseInt(options.ruleId)
      });
      this.getGoodsInfo();
    }

    if (options.grouponId) {
      this.setData({
        isGroupon: true,
      });
      this.getGrouponInfo(options.grouponId);
    }
    let that = this;
    wx.getSetting({
      success: function (res) {
        //不存在相册授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: function () {
              that.setData({
                canWrite: true
              })
            },
            fail: function (err) {
              that.setData({
                canWrite: false
              })
            }
          })
        } else {
          that.setData({
            canWrite: true
          });
        }
      }
    })
  },
  onShow: function () {
    // 页面显示
    var that = this;
    util.request(api.CartGoodsCount).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          cartGoodsCount: res.data
        });
      }
    });
  },

  //立即购买
  addFast: function (e) {
    var that = this;
    this.ok();
    this.ok1();
    //立即购买
    util.request(api.CartFastAdd, {
        goodsId: this.data.goods.id,
        number: 1
      }, "POST")
      .then(function (res) {
        if (res.errno == 0) {
          // 如果storage中设置了cartId，则是立即购买，否则是购物车购买
          try {
            wx.setStorageSync('cartId', res.data);
            wx.setStorageSync('grouponRulesId', that.data.ruleId);
            wx.setStorageSync('grouponLinkId', e.currentTarget.dataset.linkid);
            wx.navigateTo({
              url: '/pages/checkout/checkout'
            })
          } catch (e) {}

        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: res.errmsg,
            mask: true
          });
        }
      });
  },

  //添加到购物车
  addToCart: function () {
    var that = this;
    //添加到购物车
    util.request(api.CartAdd, {
        goodsId: this.data.goods.id,
        number: 1
      }, "POST")
      .then(function (res) {
        let _res = res;
        if (_res.errno == 0) {
          wx.showToast({
            title: '添加成功'
          });
          that.setData({
            cartGoodsCount: _res.data.number
          });
        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: _res.errmsg,
            mask: true
          });
        }

      });
  },
  goHome: function () {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },
  onHide: function () {},
  onUnload: function () {},

  // 外面的弹窗
  getAllGrouponInfo: function () {
    this.setData({
      showAllModal: true
    })
  },

  // 禁止屏幕滚动
  preventTouchMove: function () {},

  // 弹出层里面的弹窗
  ok: function () {
    this.setData({
      showAllModal: false
    })
  },

  // 外面的弹窗
  getOneGrouponInfo: function (event) {
    var group1 = event.currentTarget.dataset.item;
    var that = this;
    //立即购买
    util.request(api.CartFastAdd, {
        goodsId: this.data.goods.id,
        number: 1
      }, "POST")
      .then(function (res) {
        if (res.errno == 0) {
          // 如果storage中设置了cartId，则是立即购买，否则是购物车购买
          try {
            wx.setStorageSync('cartId', res.data);
            wx.setStorageSync('grouponRulesId', that.data.ruleId);
            wx.setStorageSync('grouponLinkId', group1.id);
            wx.navigateTo({
              url: '/pages/checkout/checkout'
            })
          } catch (e) {}

        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: res.errmsg,
            mask: true
          });
        }
      });
  },

  // 禁止屏幕滚动
  preventTouchMove1: function () {},

  // 弹出层里面的弹窗
  ok1: function () {
    this.setData({
      showOneModal: false
    })
  },

  closeShare: function () {
    this.setData({
      openShare: false,
    });
  },
  openCartPage: function () {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  },
  onReady: function () {},
  // 下拉刷新
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getGoodsInfo();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  //根据已选的值，计算其它值的状态
  setSpecValueStatus: function () {},
})